package com.youkeda.test.bio.server;

import com.youkeda.test.bio.handler.BIOHandler;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIO 服务端
 */
public class BIOServerListener {

    private static final ExecutorService threadPool = Executors.newFixedThreadPool(100);
    private int port = getPort();

    public void start() {
        ServerSocket server = null;
        Socket socket = null;
        try {
            // ServerSocket 启动监听端口
            server = new ServerSocket(port);
            System.out.println("BIO Server 服务器启动.........");
            socket = server.accept();

            BIOHandler serverHandler = new BIOHandler(socket);
            threadPool.execute(serverHandler);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != socket) {
                    socket.close();
                    socket = null;
                }
                if (null != server) {
                    server.close();
                    server = null;
                    System.out.println("BIO Server 服务器关闭了！！！！");
                }
                threadPool.shutdown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static int getPort() {
        Double port = (Math.random() + 1) * 10000;
        return port.intValue();
    }

    public static void main(String[] args) {
        BIOServerListener bio = new BIOServerListener();
        bio.start();
    }
}
